import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
// 假设一个场景 游客进入动物园 猴子 斑马 老虎 熊猫
// 假设进入猴子和斑马区域不需要门票 假设进入老虎和熊猫区域需要门票
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    children: [
      {
        path: 'page1',
        name: 'page1',
        component: () => import ('../views/page1')
      },
      {
        path: 'page2',
        name: 'page2',
        component: () => import ('../views/page2')
      },
      {
        path: 'page3',
        name: 'page3',
        meta: { // 路由元信息中的内容是可以自定义的
          require: true
        },
        component: () => import ('../views/page3')
      },
      {
        path: 'page4',
        name: 'page4',
        meta: {
          require: true
        },
        component: () => import ('../views/page4')
      },
    ]
  },
  {
    path: '/about',
    name: 'About',
    component: () => import ('../views/About')
  }
]

const router = new VueRouter({
  routes
})
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  // console.log(location)
  if(typeof(location)=="string"){
    var Separator = "&";
    if(location.indexOf('?')==-1) { 
      Separator='?'; 
    }
    location = location + Separator + "random=" + new Date().getTime();
  }
  return routerPush.call(this, location).catch(error=> error)
}

router.beforeEach((to, from, next) => {
  // to 要进入的页面的路由对象 from 要离开的页面的路由对象 next执行下一步
  // console.log(to)
  // if(to.name == "page3" || to.name == "page4") {
    // if(JSON.parse(localStorage.getItem('ticket'))) {
    //   next()
    // } else {
    //   alert('该区域需要门票，请买票')
    //   next('/about')
    // }
  // } else {
  //   next()
  // }
  if(to.matched.some(item => item.meta.require)) {
    if(JSON.parse(localStorage.getItem('ticket'))) {
      next()
    } else {
      alert('该区域需要门票，请买票')
      next('/about')
    }
  } else {
    next()
  }
})
export default router
